const app = getApp()

const request = (url, method, data = {}) => {
    return new Promise((resolve, reject) => {
        wx.request({
            url: app.globalData.baseURL + url,
            method: method,
            data: data,
            header: {
                'Content-Type': 'application/json',
                'X-User-ID': wx.getStorageSync('userId') || 1
            },
            success: (res) => {
                if (res.statusCode === 200) {
                    resolve(res.data)
                } else {
                    reject({
                        code: res.statusCode,
                        message: res.data.message || '请求失败'
                    })
                }
            },
            fail: (err) => {
                reject({
                    code: -1,
                    message: '网络错误，请检查网络连接'
                })
            }
        })
    })
}

export default {
    get: (url, data) => request(url, 'GET', data),
    post: (url, data) => request(url, 'POST', data),
    put: (url, data) => request(url, 'PUT', data),
    delete: (url, data) => request(url, 'DELETE', data)
}